package com.jielihaofeng.nettyadvance.chat.server.handler;

import com.jielihaofeng.nettyadvance.chat.message.LoginRequestMessage;
import com.jielihaofeng.nettyadvance.chat.message.LoginResponseMessage;
import com.jielihaofeng.nettyadvance.chat.server.service.UserServiceFactory;
import com.jielihaofeng.nettyadvance.chat.server.session.SessionFactory;
import com.jielihaofeng.nettyadvance.chat.server.session.SessionMemoryImpl;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.Set;

/**
 * @author Johnnie Wind
 * @description 登录消息处理器
 * @date 2021/11/18 14:56
 */
@ChannelHandler.Sharable
public class LoginRequestMessageHandler extends SimpleChannelInboundHandler<LoginRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, LoginRequestMessage msg) throws Exception {
        String username = msg.getUsername();
        String password = msg.getPassword();
        // 判断是否登录成功
        boolean login = UserServiceFactory.getUserService().login(username, password);
        LoginResponseMessage message;
        if (login) {
            // 绑定用户名和channel
            SessionFactory.getSession().bind(ctx.channel(), username);
            message = new LoginResponseMessage(true, "登录成功");
            SessionMemoryImpl session = (SessionMemoryImpl) SessionFactory.getSession();
            Set<String> users = session.getUsernameChannelMap().keySet();
            System.out.println("当前在线用户：" + users);
        } else {
            message = new LoginResponseMessage(false, "用户名或密码不正确");
        }
        // 发送响应消息
        ctx.writeAndFlush(message);
    }
}
